// WebSocket客户端模块 - 负责实时数据连接和管理

class WebSocketClient {
    constructor() {
        this.ws = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 2000;
        this.messageQueue = [];
        this.listeners = {};
        this.simulatedDataInterval = null;
        this.simulationActive = false;
    }

    // 连接到WebSocket服务器
    connect(url = 'ws://localhost:8080') {
        console.log('正在连接到WebSocket服务器...', url);
        
        try {
            // 在实际环境中，这里会创建真实的WebSocket连接
            // 由于是模拟环境，我们将使用模拟数据
            this.simulationActive = true;
            this.startDataSimulation();
            this.isConnected = true;
            
            // 触发连接事件
            this.emit('connected');
            realTimeSystem.emit('websocket:connected');
            
            console.log('WebSocket连接成功（模拟模式）');
        } catch (error) {
            console.error('WebSocket连接失败:', error);
            this.handleConnectionError();
        }
    }

    // 断开连接
    disconnect() {
        console.log('正在断开WebSocket连接...');
        
        if (this.simulatedDataInterval) {
            clearInterval(this.simulatedDataInterval);
            this.simulatedDataInterval = null;
        }
        
        this.isConnected = false;
        this.simulationActive = false;
        
        // 触发断开连接事件
        this.emit('disconnected');
        realTimeSystem.emit('websocket:disconnected');
        
        console.log('WebSocket连接已断开');
    }

    // 发送消息
    send(data) {
        if (this.isConnected) {
            // 在实际环境中，这里会发送真实的WebSocket消息
            console.log('发送WebSocket消息:', data);
            
            // 模拟发送成功
            return true;
        } else {
            // 如果未连接，将消息加入队列
            this.messageQueue.push(data);
            console.warn('WebSocket未连接，消息已加入队列');
            return false;
        }
    }

    // 订阅数据频道
    subscribe(channel, callback) {
        console.log(`订阅数据频道: ${channel}`);
        
        if (!this.listeners[channel]) {
            this.listeners[channel] = [];
        }
        
        this.listeners[channel].push(callback);
        
        // 返回取消订阅函数
        return () => {
            this.unsubscribe(channel, callback);
        };
    }

    // 取消订阅
    unsubscribe(channel, callback) {
        if (this.listeners[channel]) {
            this.listeners[channel] = this.listeners[channel].filter(cb => cb !== callback);
            console.log(`取消订阅数据频道: ${channel}`);
        }
    }

    // 开始数据模拟
    startDataSimulation() {
        const updateFrequency = realTimeSystem.config.updateFrequency || 1000;
        
        this.simulatedDataInterval = setInterval(() => {
            if (!this.simulationActive) return;
            
            // 生成并发送各类模拟数据
            this.generateAndSendSimulatedData();
        }, updateFrequency);
        
        console.log('数据模拟已启动，更新频率:', updateFrequency, 'ms');
    }

    // 生成并发送模拟数据
    generateAndSendSimulatedData() {
        const now = Date.now();
        
        // 1. 系统性能数据
        const systemData = {
            cpuUsage: this.generateRandomData(10, 90),
            memoryUsage: this.generateRandomData(20, 85),
            diskIO: this.generateRandomData(0, 100),
            networkIO: this.generateRandomData(0, 100),
            timestamp: now
        };
        this.emitData('system', systemData);
        
        // 2. 金融数据（模拟股票价格）
        const financeData = {
            symbol: 'AAPL',
            price: 150 + this.generateRandomData(-2, 2),
            volume: Math.floor(this.generateRandomData(10000, 1000000)),
            change: this.generateRandomData(-1, 1),
            changePercent: this.generateRandomData(-0.5, 0.5),
            timestamp: now
        };
        this.emitData('finance', financeData);
        
        // 3. 物联网设备数据
        const deviceData = {
            deviceId: `device-${Math.floor(this.generateRandomData(1, 10))}`,
            temperature: this.generateRandomData(20, 30),
            humidity: this.generateRandomData(40, 60),
            pressure: 1013 + this.generateRandomData(-10, 10),
            batteryLevel: this.generateRandomData(30, 100),
            signalStrength: this.generateRandomData(50, 100),
            timestamp: now
        };
        this.emitData('iot', deviceData);
        
        // 4. 实时数据流
        const realTimeData = {
            value: this.generateRandomData(50, 150),
            count: Math.floor(this.generateRandomData(100, 1000)),
            latency: Math.floor(this.generateRandomData(10, 200)),
            timestamp: now
        };
        this.emitData('realtime', realTimeData);
        
        // 5. 告警数据（随机触发）
        if (Math.random() > 0.95) {
            const alertLevels = ['info', 'warning', 'critical'];
            const alertTypes = ['system', 'device', 'network', 'data'];
            
            const alertData = {
                id: `alert-${Date.now()}`,
                level: alertLevels[Math.floor(Math.random() * alertLevels.length)],
                type: alertTypes[Math.floor(Math.random() * alertTypes.length)],
                source: `source-${Math.floor(this.generateRandomData(1, 5))}`,
                message: this.generateRandomAlertMessage(),
                timestamp: now
            };
            this.emitData('alert', alertData);
        }
    }

    // 生成随机数据
    generateRandomData(min, max) {
        return Math.random() * (max - min) + min;
    }

    // 生成随机告警消息
    generateRandomAlertMessage() {
        const messages = [
            'CPU使用率超过阈值',
            '内存使用过高',
            '设备连接断开',
            '数据延迟异常',
            '网络流量突增',
            '磁盘空间不足',
            '服务响应超时',
            '数据异常波动'
        ];
        return messages[Math.floor(Math.random() * messages.length)];
    }

    // 发送数据到指定频道
    emitData(channel, data) {
        // 触发本地监听器
        if (this.listeners[channel]) {
            this.listeners[channel].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`处理${channel}数据时出错:`, error);
                }
            });
        }
        
        // 触发系统事件
        realTimeSystem.emit(`data:${channel}`, data);
    }

    // 触发事件
    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`处理${event}事件时出错:`, error);
                }
            });
        }
    }

    // 处理连接错误
    handleConnectionError() {
        this.isConnected = false;
        
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            
            setTimeout(() => {
                this.connect();
            }, this.reconnectDelay * this.reconnectAttempts);
        } else {
            console.error('达到最大重连次数，停止重连');
            this.emit('connectionFailed');
            realTimeSystem.emit('websocket:connectionFailed');
        }
    }

    // 获取连接状态
    getStatus() {
        return {
            connected: this.isConnected,
            simulation: this.simulationActive,
            reconnectAttempts: this.reconnectAttempts,
            messageQueueLength: this.messageQueue.length
        };
    }

    // 配置重连参数
    configureReconnect(options) {
        this.maxReconnectAttempts = options.maxAttempts || this.maxReconnectAttempts;
        this.reconnectDelay = options.delay || this.reconnectDelay;
    }

    // 清空消息队列
    clearMessageQueue() {
        this.messageQueue = [];
        console.log('WebSocket消息队列已清空');
    }

    // 暂停数据模拟
    pauseSimulation() {
        if (this.simulatedDataInterval) {
            clearInterval(this.simulatedDataInterval);
            this.simulatedDataInterval = null;
        }
        this.simulationActive = false;
        console.log('数据模拟已暂停');
    }

    // 恢复数据模拟
    resumeSimulation() {
        if (!this.simulationActive) {
            this.startDataSimulation();
            this.simulationActive = true;
        }
        console.log('数据模拟已恢复');
    }
}

// 创建并注册WebSocket客户端实例
const webSocketClient = new WebSocketClient();
realTimeSystem.registerModule('webSocketClient', webSocketClient);

// 导出WebSocket客户端
window.webSocketClient = webSocketClient;